<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/03/06 05:15:17 $)
// $RCSfile: functions_comments.php,v $ : $Revision: 1.8 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* ###############################################
* GENERAL FUNCTIONS
* ###############################################
*/

/**
* Render the comment data for client area
*/
function renderClientComments($commenttype, $typeid)
{
	global $dbCore, $_SWIFT, $template;

	// First load all the comments
	$commentlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."comments` AS comments LEFT JOIN `". TABLE_PREFIX ."commentdata` AS commentdata ON (comments.commentid = commentdata.commentid) WHERE comments.commenttype = '". intval($commenttype) ."' AND comments.isapproved = '1' AND comments.typeid = '". intval($typeid) ."';");
	$row = 0;
	while ($dbCore->nextRecord())
	{
		if ($row == 0)
		{
			$row = 1;
		} else {
			$row = 0;
		}
		$commentlist[$dbCore->Record["commentid"]]["fullname"] = htmlspecialchars($dbCore->Record["fullname"]);
		$commentlist[$dbCore->Record["commentid"]]["email"] = htmlspecialchars($dbCore->Record["email"]);
		$commentlist[$dbCore->Record["commentid"]]["contents"] = nl2br(htmlspecialchars($dbCore->Record["contents"]));
		$commentlist[$dbCore->Record["commentid"]]["date"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $dbCore->Record["dateline"]);
		$commentlist[$dbCore->Record["commentid"]]["rownumber"] = $row;
	}
	$template->assign("commentlcount", count($commentlist));
	$template->assign("commentlist", $commentlist);
	$template->assign("commenttype", $commenttype);
	$template->assign("commenttypeid", $typeid);
}

/**
* Insert a new Comment into the system
*/
function insertComment($commenttype, $typeid, $fullname, $email, $contents)
{
	global $_SWIFT, $dbCore;

	if ($_SWIFT["settings"]["g_commentsapproval"] == 1)
	{
		$isapproved = 0;
	} else {
		$isapproved = 1;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."comments` (`typeid`, `commenttype`, `fullname`, `email`, `isapproved`, `dateline`) VALUES ('". intval($typeid) ."', '". intval($commenttype) ."', '". $dbCore->escape($fullname) ."', '". $dbCore->escape($email) ."', '". intval($isapproved) ."', '". DATENOW ."');");
	$commentid = $dbCore->lastInsertId();
	if (!$commentid)
	{
		return false;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."commentdata` (`commentid`, `contents`) VALUES ('". intval($commentid) ."', '". $dbCore->escape($contents) ."');");

	resetCommentTypeCount($commenttype, $typeid);
	rebuildCommentCache();

	return $commentid;
}

/**
* Builds a type list for resetting comment data
*/
function buildTypeList($commentidlist)
{
	global $dbCore;

	$resetlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."comments` WHERE `commentid` IN (". buildIN($commentidlist) .");");
	while ($dbCore->nextRecord())
	{
		if (!in_array($dbCore->Record["typeid"], $resetlist[$dbCore->Record["commenttype"]]))
		{
			$resetlist[$dbCore->Record["commenttype"]][] = $dbCore->Record["typeid"];
		}
	}

	return $resetlist;
}

/**
* Goes through the type list and resets the comments
*/
function resetTypeList($resetlist)
{
	if (!_is_array($resetlist))
	{
		return false;
	}

	foreach ($resetlist as $key=>$val)
	{
		foreach ($val as $typekey=>$typeval)
		{
			resetCommentTypeCount($key, $typeval);
		}
	}
}

/**
* Delete the given comments
*/
function deleteComments($commentidlist)
{
	global $dbCore;

	if (!_is_array($commentidlist))
	{
		return false;
	}

	$typelist = buildTypeList($commentidlist);

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."comments` WHERE `commentid` IN (". buildIN($commentidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."commentdata` WHERE `commentid` IN (". buildIN($commentidlist) .");");

	resetTypeList($typelist);
	rebuildCommentCache();

	return true;
}

/**
* Update the given comments
*/
function updateComment($commentid, $fullname, $email, $contents)
{
	global $dbCore;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."comments` SET `fullname` = '". $dbCore->escape($fullname) ."', `email` = '". $dbCore->escape($email) ."' WHERE `commentid` = '". intval($commentid) ."';");

	$dbCore->query("UPDATE `". TABLE_PREFIX ."commentdata` SET `contents` = '". $dbCore->escape($contents) ."' WHERE `commentid` = '". intval($commentid) ."';");

	return true;
}

/**
* Approve the given comments
*/
function approveComments($commentidlist)
{
	global $dbCore;

	if (!_is_array($commentidlist))
	{
		return false;
	}

	$typelist = buildTypeList($commentidlist);

	$dbCore->query("UPDATE `". TABLE_PREFIX ."comments` SET `isapproved` = '1' WHERE `commentid` IN (". buildIN($commentidlist) .");");

	resetTypeList($typelist);
	rebuildCommentCache();

	return true;
}

/**
* Unapprove the specified comments
*/
function unapproveComments($commentidlist)
{
	global $dbCore;

	if (!_is_array($commentidlist))
	{
		return false;
	}

	$typelist = buildTypeList($commentidlist);

	$dbCore->query("UPDATE `". TABLE_PREFIX ."comments` SET `isapproved` = '0' WHERE `commentid` IN (". buildIN($commentidlist) .");");

	resetTypeList($typelist);
	rebuildCommentCache();

	return true;
}

/**
* Recalculate the Comments for the given type
*/
function resetCommentTypeCount($commenttype, $typeid)
{
	global $dbCore;

	// First calculate the total comments under the given type
	$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totalcomments FROM `". TABLE_PREFIX ."comments` WHERE `commenttype` = '". intval($commenttype) ."' AND `isapproved` = '1' AND `typeid` = '". intval($typeid) ."';");
	if (empty($_total["totalcomments"]))
	{
		$totalcomments = "0";
	} else {
		$totalcomments = $_total["totalcomments"];
	}

	// Now update the data accordingly
	switch ($commenttype)
	{
		case COMMENT_KNOWLEDGEBASE:
			$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."kbarticles` SET `totalcomments` = '". intval($totalcomments) ."' WHERE `kbarticleid` = '". intval($typeid) ."';");
			break;
		case COMMENT_DOWNLOADS:
			$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."downloaditems` SET `totalcomments` = '". intval($totalcomments) ."' WHERE `downloaditemid` = '". intval($typeid) ."';");
			break;
		CASE COMMENT_NEWS:
			$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."news` SET `totalcomments` = '". intval($totalcomments) ."' WHERE `newsid` = '". intval($typeid) ."';");
			break;
		CASE COMMENT_TROUBLESHOOTER:
			$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."troubleshootersteps` SET `totalcomments` = '". intval($totalcomments) ."' WHERE `troubleshooterid` = '". intval($typeid) ."';");
			break;
	}

	// Now all the data should be updated.

	return true;
}

/**
* Rebuilds the comment cache
*/
function rebuildCommentCache()
{
	global $dbCore, $_SWIFT, $datastore;

	$commentcache = array();
	$dbCore->query("SELECT COUNT(*) as totalitems, `commenttype`, `isapproved` FROM `". TABLE_PREFIX ."comments` GROUP BY `commenttype`, `isapproved`;");
	while ($dbCore->nextRecord())
	{
		if ($dbCore->Record["isapproved"] == "0" && !empty($dbCore->Record["totalitems"]))
		{
			$commentcache[$dbCore->Record["commenttype"]] = $dbCore->Record["totalitems"];
		}
	}

	$datastore->update("commentcache", $commentcache);
}

/**
* Get corresponding URL
*/
function getCommentURL($commenttype)
{
	switch ($commenttype)
	{
		case COMMENT_KNOWLEDGEBASE:
			$commenturl = "index.php?_m=knowledgebase&_a=comments";
			break;
		case COMMENT_DOWNLOADS:
			$commenturl = "index.php?_m=downloads&_a=comments";
			break;
		CASE COMMENT_NEWS:
			$commenturl = "index.php?_m=news&_a=comments";
			break;
		CASE COMMENT_TROUBLESHOOTER:
			$commenturl = "index.php?_m=troubleshooter&_a=comments";
			break;
	}
	return $commenturl;
}


/**
* Renders the Comment Edit form
*/
function renderCommentForm()
{
	global $_SWIFT;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["editcomment"]);

	printTextRow("fullname", $_SWIFT["language"]["fullname"], $_SWIFT["language"]["fullname"], "text", $_POST["fullname"]);

	printTextRow("email", $_SWIFT["language"]["email"], $_SWIFT["language"]["email"], "text", $_POST["email"]);

	printDescRow($_SWIFT["language"]["contents"]);
	$data = array();
	$data[0]["value"] = '<textarea style="WIDTH:100%;" name="contents" cols="100" rows="15">'. htmlspecialchars($_POST["contents"]) .'</textarea>'.SWIFT_CRLF;
	$data[0]["align"] = "center";
	$data[0]["colspan"] = "2";

	printDataRow($data);

	printSubmitRow($_SWIFT["language"]["update"]);

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", "editcomment");
	addHiddenField("step", "1");
	addHiddenField("commentid", $_POST["commentid"]);

	printFormEnd();
}

/**
* ###############################################
* COMMENT GRID FUNCTIONS
* ###############################################
*/

/**
* Render the Comment Grids based on the given commenttype
*/
function renderCommentGrids($commenttype)
{
	global $_SWIFT, $dbCore, $infomessage;

	if ($_GET["do"] == "delete" && !empty($_GET["commentid"]))
	{
		$infomessage = $_SWIFT["language"]["commentdelconfirm"];

		deleteComments(array($_GET["commentid"]));
	} else if ($_GET["do"] == "approve" && !empty($_GET["commentid"])) {
		$infomessage = $_SWIFT["language"]["commentstatusconfirm"];
		approveComments(array($_GET["commentid"]));
	} else if ($_GET["do"] == "unapprove" && !empty($_GET["commentid"])) {
		$infomessage = $_SWIFT["language"]["commentstatusconfirm"];
		unapproveComments(array($_GET["commentid"]));
	}
	

	if (!empty($_REQUEST["updatecomment"])) {
		$infomessage = sprintf($_SWIFT["language"]["commentupdconfirm"], htmlspecialchars($_REQUEST["updatecomment"]));
	}

	$commenturl = getCommentURL($commenttype);

	$commentslist = array();
	$dbCore->query('SELECT * FROM `'. TABLE_PREFIX .'comments` AS comments LEFT JOIN `'. TABLE_PREFIX .'commentdata` AS commentsdata ON (comments.commentid = commentsdata.commentid) WHERE comments.commenttype = \''. intval($commenttype) .'\' AND comments.isapproved = \'0\' ORDER BY comments.dateline ASC;');
	while ($dbCore->nextRecord())
	{
		$commentslist[] = $dbCore->Record;
	}

	if (count($commentslist))
	{
		printMainTableHeader($_SWIFT["language"]["unapprovedcomments"]);

		$colarray[0]["align"] = "left";
		$colarray[0]["nowrap"] = true;
		$colarray[0]["value"] = $_SWIFT["language"]["fullname"];
		$colarray[1]["align"] = "center";
		$colarray[1]["width"] = "300";
		$colarray[1]["value"] = $_SWIFT["language"]["email"];
		$colarray[2]["align"] = "center";
		$colarray[2]["width"] = "160";
		$colarray[2]["value"] = $_SWIFT["language"]["date"];
		$colarray[3]["align"] = "center";
		$colarray[3]["width"] = "250";
		$colarray[3]["value"] = $_SWIFT["language"]["options"];
		printDataRow($colarray, "tabletitlerow");

		foreach ($commentslist as $key=>$record)
		{
			$colarray = array();
			$colarray[0]["align"] = "left";
			$colarray[0]["value"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="0"><tr><td width="1" align="left"><img src="'. $_SWIFT["themepath"] .'icon_commentunappr.gif" /></td><td><span class="smalltext">&nbsp;'.htmlspecialchars($record["fullname"]).'</span></td></tr></table>';
			$colarray[1]["align"] = "center";
			$colarray[1]["value"] = htmlspecialchars($record["email"]);
			$colarray[2]["align"] = "center";
			$colarray[2]["value"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);
			$colarray[3]["align"] = "center";
			$colarray[3]["value"] = '<a href="'.$commenturl.'&do=approve&commentid='. $record["commentid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_approvecomment.gif" border="0">&nbsp;'. $_SWIFT["language"]["approve"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="index.php?_m=core&_a=editcomment&commentid='. $record["commentid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \''. $commenturl .'&do=delete&commentid='. $record["commentid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';
			printDataRow($colarray);

			$colarray = array();
			$colarray[0]["align"] = "left";
			$colarray[0]["colspan"] = "4";
			$colarray[0]["value"] = nl2br(htmlspecialchars($record["contents"]));
			printDataRow($colarray);

		}
		printMainTableFooter();
		echo "<BR />";
	}
	
	$options["recordsperpage"] = "5";
	$options["sortby"] = "comments.dateline";
	$options["sortorder"] = "desc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteComments";
	$options["massaction"][1]["title"] = $_SWIFT["language"]["unapprove"];
	$options["massaction"][1]["callback"] = "_maUnapproveComments";

	$options["idname"] = "commentid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["fullname"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'comments` AS comments WHERE comments.fullname LIKE \'%$_searchstr%\' AND `commenttype` = \''. intval($commenttype) .'\' AND `isapproved` = \'1\' $_sortjoin;';

	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["email"];
	$options["advancedsearch"][1]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'comments` AS comments WHERE comments.email LIKE \'%$_searchstr%\' AND `commenttype` = \''. intval($commenttype) .'\' AND `isapproved` = \'1\' $_sortjoin;';

	$options["advancedsearch"][2]["title"] = $_SWIFT["language"]["contents"];
	$options["advancedsearch"][2]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'comments` AS comments LEFT JOIN `'. TABLE_PREFIX .'commentdata` AS commentdata ON (comments.commentid = commentdata.commentid) WHERE comments.fullname LIKE \'%$_searchstr%\' AND `commenttype` = \''. intval($commenttype) .'\' AND `isapproved` = \'1\' $_sortjoin;';

	$options["callback"] = "_commentFields";

	$fields[0]["name"] = "comments.fullname";
	$fields[0]["title"] = $_SWIFT["language"]["fullname"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "comments.email";
	$fields[1]["title"] = $_SWIFT["language"]["email"];
	$fields[1]["width"] = "300";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "comments.dateline";
	$fields[2]["title"] = $_SWIFT["language"]["date"];
	$fields[2]["width"] = "160";
	$fields[2]["align"] = "center";

	$fields[3]["type"] = "custom";
	$fields[3]["name"] = "options";
	$fields[3]["title"] = $_SWIFT["language"]["options"];
	$fields[3]["width"] = "250";
	$fields[3]["align"] = "center";

	$grid = new Grid();

	$grid->start("comments", $_SWIFT["language"]["approvedcomments"], 'SELECT * FROM `'. TABLE_PREFIX .'comments` AS comments WHERE `commenttype` = \''. intval($commenttype) .'\' AND `isapproved` = \'1\' $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'comments` WHERE `commenttype` = \''. intval($commenttype) .'\' AND `isapproved` = \'1\';', 'SELECT * FROM `'. TABLE_PREFIX .'comments` AS comments LEFT JOIN `'. TABLE_PREFIX .'commentdata` AS commentdata ON (comments.commentid = commentdata.commentid) WHERE comments.fullname LIKE \'%$_searchstr%\' AND `commenttype` = \''. intval($commenttype) .'\' AND `isapproved` = \'1\' $_sortjoin;', $fields, $options);

	global $infomessage;
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	$grid->display("comments");

	echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .' <img src="'. $_SWIFT["themepath"] .'icon_commentunappr.gif" border="0" /> '. $_SWIFT["language"]["unapprovedcomments"].'</span>';
}

/**
* Mass Delete Comments (Mahesh Slaria)
*/
function _maDeleteComments()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]))
	{
		return false;
	}

	deleteComments($_POST["itemid"]);
}


/**
* Mass Unapprove comments. (Mahesh Slaria)
*/
function _maUnapproveComments()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]))
	{
		return false;
	}

	unapproveComments($_POST["itemid"]);
}


/**
* Renders the Comment Field Data
*/
function _commentFields($arg)
{
	global $_SWIFT, $_sladays;
	$record = &$arg[0];
	$fields = &$arg[1];

	$commenturl = getCommentURL($record["commenttype"]);

	$record["comments.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);

	$record["comments.fullname"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="0"><tr><span class="smalltext">&nbsp;'.htmlspecialchars($record["fullname"]).'</span></td></tr></table>';

	$record["comments.email"] = htmlspecialchars($record["email"]);

	$record["options"] = '<a href="'.$commenturl.'&do=unapprove&commentid='. $record["commentid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_unapprovecomment.gif" border="0">&nbsp;'. $_SWIFT["language"]["unapprove"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="index.php?_m=core&_a=editcomment&commentid='. $record["commentid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \''. $commenturl .'&do=delete&commentid='. $record["commentid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';

	return $record;
}
?>